package com.example.lp.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Author by lp,on 2021/2/22/022,15:16.
 */
public class MyContentProvider extends ContentProvider {
    private static String TAG = "MyContentProvider";
    private static String AUTHORITY = "com.lp.test.myprovider";

    //数据改变后指定通知的Uri
    public static final Uri BOOK_URI = Uri.parse("content://" + AUTHORITY + "/book");
    //匹配成功后的匹配码
    private static final int MATCH_CODE = 100;
    private static UriMatcher uriMatcher;
    private SQLiteDatabase db;

    static {
        //匹配不成功返回NO_MATCH(-1)
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //添加我们需要匹配的uri
        uriMatcher.addURI(AUTHORITY, "book", MATCH_CODE);
    }

    //contentprovider的创建，进行初始化工作
    //系统回调，运行在主线程中，其余方法由外界回调，运行在binder线程池中
    @Override
    public boolean onCreate() {
        Log.i(TAG, "MyContentProvider onCreate: ");
        MyDbHelper dbHelper = new MyDbHelper(getContext());
        db = dbHelper.getWritableDatabase();
        db.execSQL("delete from " + MyDbHelper.BOOK_TABLE);
        db.execSQL("insert into book values(1,'testbook');");
        return false;
    }

    private String getTableName(Uri uri) {
        int match = uriMatcher.match(uri);
        if (match == MATCH_CODE) {
            Log.i(TAG, "getTableName: ");
            return MyDbHelper.BOOK_TABLE;
        }
        return null;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.i(TAG, "query: ");
        String table = getTableName(uri);
        return db.query(table, projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    /*
     * 返回一个uri请求对应的 MIME类型
     * 如图片、视屏等
     * 如果不关心类型，可以返回null或者 * /*
     * */
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.i(TAG, "getType: ");
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Log.i(TAG, "insert: ");
        String table=getTableName(uri);
        db.insert(table,null,values);
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.i(TAG, "delete: ");
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.i(TAG, "update: ");
        return 0;
    }
}
